package controller.stocket;


//import config.GetHttpSessionConfigurator;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import service.SubmitMessage;
import util.Jwt;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value="/chat/message/{key}")
public class ChatEndPointController {
    private static Map<String,Session> mapSession=new ConcurrentHashMap<>();
    private static int countUserOnline=0;
    private String id_from;



    @OnOpen
    public void init(@PathParam("key") String key, Session session) throws IOException {
        //key
        countUserOnline++;//在线人数
        if(Jwt.decrypt(key)){
            //当前的用户登录没有过期
            this.id_from=Jwt.getData(key);
            mapSession.put(id_from,session);
        }else{
            session.getAsyncRemote().sendText("key_time_over");
            session.close();
            //
        }
    }
    @OnMessage
    public void onMessage(String message){//message 至少20个字符
        System.out.println(message);
        Map.Entry<String,String> id_message=ChatEndPointController.getToId(message);
        String id_to=id_message.getKey();//id_to
        String mess=id_message.getValue();//信息
        System.out.println(id_from+"  "+id_to+"  "+mess);
//        this.submit=new SubmitMessage();
        SubmitMessage.submitMessage(this.id_from,id_to,mapSession.get(id_to),mess);//发送信息
    }
    @OnClose
    public void onclose(Session session){

        mapSession.remove(this.id_from);
        countUserOnline--;
    }
    private synchronized static Map.Entry<String,String> getToId(String message){
        String id_to=message.substring(message.length()-20);
        int x=0;
        while(Character.isDigit(id_to.charAt(x))){
            x++;
        }
        String mes=message.substring(0,message.length()-20);
        id_to=id_to.substring(x);
        return Map.entry(id_to,mes);
    }


}
